//
//  ZJCycleImageView.m
//  CycleImageScrollDemo
//
//  Created by 郑佳 on 16/6/15.
//  Copyright © 2016年 Triangle. All rights reserved.
//

#import "ZJCycleImageView.h"
#import "ZJCycleImageFlowLayout.h"
#import "WeakTargetObject.h"
#import "ZJCycleImageModel.h"

#define Page_Control_Margin 10

#define ZJCycleImageViewCell_ReuseIdentifier @"ZJCycleImageViewCell_ReuseIdentifier"
@interface ZJCycleImageView()<UICollectionViewDataSource,UICollectionViewDelegate>

@end
@implementation ZJCycleImageView{
    
    UICollectionView *_collectionView;
    UIView           *_lineView;
    NSArray          *_bannerArray;
    NSArray          *_titleArray;
    NSArray          *_detailArray;
    UIPageControl    *_pageControl;// 分页控件
    NSTimer          *_timer;
    ZJCycleImageViewStyle   _style;
    ZJCycleImageModel *_imageModel;
    
    NSMutableArray *_tempArray;
    
}


- (instancetype)initWithFrame:(CGRect)frame banners:(NSArray *)banners{

    if (self = [super initWithFrame:frame]) {
        _tempArray = @[].mutableCopy;
        _bannerArray = banners;
        [self setupCollectionView];
        
        //设置分页指示器的颜色
        self.backgroundColor = [UIColor whiteColor];

        self.titleColor = [UIColor darkTextColor];
        self.detailTitleColor = [UIColor darkTextColor];
        self.titleFoneSize = 14;
        self.detaiTitleFoneSize = 12;
        self.currentPageIndicatorColor = [UIColor whiteColor];
        self.otherPageIndicatorColor = [UIColor darkGrayColor];
        self.hidesForSinglePage = YES;
        self.pageControlIconSize = CGSizeMake(10, 10);
        
        if (banners.count) {
            //异步主队列目的为了 先执行collectionView数据源方法返回后滚动到指定位置
            dispatch_async(dispatch_get_main_queue(), ^{
                // 在主线程空闲时执行block
                NSIndexPath *indexPath = [NSIndexPath indexPathForItem:_bannerArray.count inSection:0];
                [_collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
                if (banners.count > 1) {
                    [self p_addTimer];
                }
            });
        }
        
        for (NSString *imageURL in banners) {
            _imageModel = [[ZJCycleImageModel alloc]init];
            _imageModel.imageURL = imageURL;
            [_tempArray addObject:_imageModel];
        }
    }
    return self;

}

- (instancetype)initWithFrame:(CGRect)frame banners:(NSArray *)banners titles:(NSArray *)titles style:(ZJCycleImageViewStyle)style {
    
    if (self = [self initWithFrame:frame banners:banners]) {
        _titleArray = titles;
        _style = style;
        for (NSInteger index = 0; index < _tempArray.count; index++) {
            ZJCycleImageModel *model = _tempArray[index];
            model.title = _titleArray[index];
        }
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame banners:(NSArray *)banners titles:(NSArray *)titles detailTitles:(NSArray *)detailTitles style:(ZJCycleImageViewStyle)style {
    if (self = [self initWithFrame:frame banners:banners titles:titles style:style]) {
        _detailArray = detailTitles;
        for (NSInteger index = 0; index < _tempArray.count; index++) {
            ZJCycleImageModel *model = _tempArray[index];
            model.detailTitle = _detailArray[index];
        }
    }
    return self;
}

- (void)setupCollectionView{
    
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:[[ZJCycleImageFlowLayout alloc]init]];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.frame = self.bounds;
    _collectionView.bounces = NO;
    _collectionView.backgroundColor = self.backgroundColor;
    [_collectionView registerClass:[ZJCycleImageViewCell class] forCellWithReuseIdentifier:ZJCycleImageViewCell_ReuseIdentifier];
    [self addSubview:_collectionView];
    
    _lineView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetHeight(_collectionView.frame), self.frame.size.width, 0.5)];
    _lineView.backgroundColor = [UIColor colorWithRed:229.0/255.0 green:229.0/255.0 blue:229.0/255.0 alpha:1.0];
    [self addSubview:_lineView];
}

- (void)setBackgroundColor:(UIColor *)backgroundColor {
    _backgroundColor = backgroundColor;
    _collectionView.backgroundColor = backgroundColor;
}

/** 创建分页指示器 */
- (void)setupPageControl{
    
    if ((_bannerArray.count <= 1) && self.hidesForSinglePage) {
        return;
    }
    _pageControl = [[UIPageControl alloc] init];
    _pageControl.numberOfPages = _bannerArray.count;
    _pageControl.currentPageIndicatorTintColor = self.currentPageIndicatorColor;
    _pageControl.pageIndicatorTintColor = self.otherPageIndicatorColor;
    _pageControl.userInteractionEnabled = NO;
    
    CGSize size = CGSizeMake(_bannerArray.count * self.pageControlIconSize.width * 1.2, self.pageControlIconSize.height);
    CGFloat x = (self.frame.size.width - size.width) * 0.5;
    CGFloat y = self.frame.size.height - size.height - Page_Control_Margin;
    if (self.pageControlAliment == ZJCycleImageViewPageContolAlimentRight) {
        x = self.frame.size.width - size.width - Page_Control_Margin;
    }
    if (self.pageControlAliment == ZJCycleImageViewPageContolAlimentLeft){
        x = Page_Control_Margin;
    }

    _pageControl.frame = CGRectMake(x, y, size.width, size.height);
    
    [self addSubview:_pageControl];
}

- (void)setShowPageControl:(BOOL)showPageControl {
    _showPageControl = showPageControl;
    _pageControl.hidden = !showPageControl;
}

/** 设置分页图片的大小 */
- (void)setPageControlIconSize:(CGSize)pageControlIconSize {
    _pageControlIconSize = pageControlIconSize;
    
    [self setupPageControl];
}

- (void)setCurrentPageIndicatorColor:(UIColor *)currentPageIndicatorColor {
    _currentPageIndicatorColor = currentPageIndicatorColor;
    _pageControl.currentPageIndicatorTintColor = currentPageIndicatorColor;
}

- (void)setOtherPageIndicatorColor:(UIColor *)otherPageIndicatorColor {
    _otherPageIndicatorColor = otherPageIndicatorColor;
    _pageControl.pageIndicatorTintColor = otherPageIndicatorColor;
}

/** 添加定时器方法 */
- (void)p_addTimer{
    
    if (_timer) return;
    _timer = [WeakTargetObject scheduledTimerWithTimeInterval:4.0 target:self selector:@selector(s_nextImage) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];

}

/** 移除定时器方法 */
- (void)p_removeTimer{
    [_timer invalidate];
    _timer = nil;
}

- (void)closeLoop {
    
    if (_bannerArray == nil || _bannerArray.count == 1) {
        [self p_removeTimer];
        _collectionView.scrollEnabled = NO;
    } else {
        _collectionView.scrollEnabled = YES;
        _timer ? [self p_removeTimer] : [self p_addTimer];
    }
}

- (void)s_nextImage{
    
    NSInteger page = _collectionView.contentOffset.x / _collectionView.frame.size.width; //计算当前显示的页号
    [_collectionView setContentOffset:CGPointMake((page + 1) * _collectionView.frame.size.width, 0) animated:YES];// 设置偏移量
}

#pragma mark - collectionView的数据源方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
   
    return _bannerArray.count * 3;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    ZJCycleImageViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ZJCycleImageViewCell_ReuseIdentifier forIndexPath:indexPath];
    cell.style = _style;
    cell.backgroundColor = [UIColor clearColor];
    // 取模是防止数组越界
    cell.model = _tempArray[indexPath.item % _tempArray.count];
    [cell setTitleColor:self.titleColor fontSize:self.titleFoneSize];
    [cell setDetailTitleColor:self.detailTitleColor fontSize:self.detaiTitleFoneSize];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSInteger index = indexPath.item % _tempArray.count;
    if (index > _tempArray.count - 1) {
        return;
    }
    if ([self.delegate respondsToSelector:@selector(cycleImageViewDidClick:)]) {
        [self.delegate cycleImageViewDidClick:index];
    }
}

#pragma mark - 当用户开始拖拽的时候，清除定时器
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self p_removeTimer];
}

#pragma mark - 滑动翻页
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSInteger itemIndex = (scrollView.contentOffset.x + self.frame.size.width * 0.5) / self.frame.size.width;

    if (!_tempArray.count) return;
    
    NSInteger index = itemIndex % _tempArray.count;
    if (index > _tempArray.count - 1) {
        return;
    }
    NSInteger indexOnPageControl = index;
    
    if (_pageControl != nil) {
        _pageControl.currentPage = indexOnPageControl;
    }

}

#pragma mark - 当自动滚动停止滚动动画时调用该方法
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    [self scrollViewDidEndDecelerating:scrollView];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
 
    NSInteger itemIndex = scrollView.contentOffset.x / self.frame.size.width;
    if (itemIndex == 0 || itemIndex == [_collectionView numberOfItemsInSection:0]-1) {
        
        if (itemIndex == 0) {// 当滑动到第0张时
            itemIndex = _tempArray.count;
        }else{// 滑到最后一张
            itemIndex = _tempArray.count - 1;
        }
    }
    scrollView.contentOffset = CGPointMake(itemIndex * scrollView.bounds.size.width, 0);// 设置偏移量
    [self p_addTimer];// 当用户拖拽离开时，重新添加定时器
    
}

@end
